#!/usr/bin/python
# -*- coding: utf-8 -*-
import ftplib
import ftplib

#-------------------------------------------------
#Create At: 2008-6-11 上午01:57:27 
#Create By: Fla.sam
#
#DESC: test header
#
#-------------------------------------------------

import httplib
import urlparse
import socket
import ftplib
import os
import sys
import subprocess

h = '''Spider mode enabled. Check if remote file exists.
--2008-06-11 01:30:30--  http://www.x-ways.net/winhex.zip
Resolving www.x-ways.net... 212.227.190.78
Connecting to www.x-ways.net|212.227.190.78|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 302 Found
  Date: Tue, 10 Jun 2008 17:30:15 GMT
  Server: Apache/1.3.34 Ben-SSL/1.55
  Location: http://www.x-ways.net/cgi-bin/winhex.cgi
  Keep-Alive: timeout=2, max=199
  Connection: Keep-Alive
  Content-Type: text/html; charset=iso-8859-1
Location: http://www.x-ways.net/cgi-bin/winhex.cgi [following]
Spider mode enabled. Check if remote file exists.
--2008-06-11 01:30:30--  http://www.x-ways.net/cgi-bin/winhex.cgi
Connecting to www.x-ways.net|212.227.190.78|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 302 Found
  Date: Tue, 10 Jun 2008 17:30:16 GMT
  Server: Apache/1.3.34 Ben-SSL/1.55
  Location: http://www.muenster.de/~sf/winhex.zip
  Keep-Alive: timeout=2, max=199
  Connection: Keep-Alive
  Content-Type: text/html; charset=iso-8859-1
Location: http://www.muenster.de/~sf/winhex.zip [following]
Spider mode enabled. Check if remote file exists.
--2008-06-11 01:30:31--  http://www.muenster.de/~sf/winhex.zip
Resolving www.muenster.de... 195.202.32.196
Connecting to www.muenster.de|195.202.32.196|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Date: Tue, 10 Jun 2008 17:30:19 GMT
  Server: Apache
  Last-Modified: Mon, 02 Jun 2008 10:39:06 GMT
  ETag: "2b5d30-15cd66-9ad78680"
  Accept-Ranges: bytes
  Content-Length: 1428838
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Content-Type: application/zip
Length: 1428838 (1.4M) [application/zip]
Remote file exists.'''

def split_url( u ):
    _u = urlparse.urlsplit( u )
    return '%s' % _u[1], '%s?%s%s' % _u[2:]

class BotError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def do_analyze_header(u='https://www.x-ways.net/winhex.zip'):
    
    protocol = urlparse.urlparse(u)[0]
    _i_host, _i_path = split_url( u )
    if protocol.lower() == 'http':
        conn = httplib.HTTPConnection( _i_host )
    elif protocol.lower() == 'https':
        conn = httplib.HTTPSConnection( _i_host )
    else:
        raise BotError, 'Unknow protocol'
    conn.request( "GET", _i_path )
    r1 = conn.getresponse()
    if r1.status == 200:
        return r1
    elif r1.status == 301 or r1.status == 302:
        ru = r1.getheader('location')
        return do_analyze_header(ru)
    else:
        raise BotError, 'read http header error'


          
def do_analyse_ftp( u='ftp://ftp.drweb.com/pub/drweb/cureit/launch.exe' ):
    
    # class for read stdout
    dirList = []
    class CollectDirOutput:
        def write( self, string ):
            if len( string ) > 1:
                dirList.append( string )
                
    # now read ftp
    _protocol, _host, _full_path = urlparse.urlparse( u )[:3]
    
    try:
        f = ftplib.FTP( _host )
    except socket.error:
        l_size = None
        l_modified_time = None
        l_status = None
        l_header = 'Connect ftp server Error'
        return l_size, l_modified_time, l_status, l_header
    
    try:
        f.login()
    except ftplib.error_perm:
        l_size = None
        l_modified_time = None
        l_status = None
        l_header = 'Login ftp server Error, '
        return l_size, l_modified_time, l_status, l_header
    
    _path , _basename = os.path.split( _full_path )
    if _basename != '':
        # read file size
        try:
            l_size = f.size( _full_path )
        except ftplib.error_perm:
            l_size = None
        # read file last modified time
        try:
            l_modified_time = f.sendcmd( 'MDTM %s' % _full_path ).split()[1]
        except: # eat all error
            l_modified_time = None
    else:
        l_size = None
        l_modified_time = None
    
    #read dir stdout
    oldout = sys.stdout
    sys.stdout = CollectDirOutput() #@UndefinedVariable
    f.dir( _full_path )
    sys.stdout = oldout
    
    # close ftp connection
    f.close()
    
    # output dir string
    if len( dirList ) == 1:
        l_header =  dirList[0]
        l_status = 'OK'
    elif dirList == []:
        l_status = None
        l_header = 'Not such directory or file'
    else:
        l_status = 'OK'
        l_header = str( dirList )
    
    return l_size, l_modified_time, l_status, l_header

def main():
    #print do_analyze_header().getheaders()
    #print do_analyse_ftp()
    PIPE = subprocess.PIPE
    p = subprocess.Popen( 'lynx -source %s' % 'http://www.emeditor.com/modules/download2/', shell=True, stdout=PIPE, stderr=PIPE)
    ( child_stdin, child_stdout, child_stderr ) = ( p.stdin, p.stdout, p.stderr )
    html_source = child_stdout.read()
    print html_source

if __name__ == '__main__':
    main()
